﻿<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="urlwatcher" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
 <script language="CS" runat="server">
   static string sAuthTokenName = "";
   static string sAuthParamName = "";
   static string sTargetUrlName = "";
   static byte[] secretKey = null;
   ASCIIEncoding textConverter = new ASCIIEncoding();
     
   void Page_Load(object sender, System.EventArgs e) 
   {
       string sSharedSecret = WebConfigurationManager.AppSettings["urlwatcher-shared-secret"];
       secretKey = textConverter.GetBytes(sSharedSecret);
       sAuthTokenName = WebConfigurationManager.AppSettings["urlwatcher-authorization-token"];
       sAuthParamName = WebConfigurationManager.AppSettings["urlwatcher-authorization-parameter"];
       sTargetUrlName = WebConfigurationManager.AppSettings["urlwatcher-target-url-parameter"];
   }

   private string encryptToken(string token) 
   {
       byte[] encryptedData = TokenUtils.encryptECB(secretKey, PaddingMode.ISO10126, textConverter.GetBytes(token));
       return HttpUtility.UrlEncode(System.Convert.ToBase64String(encryptedData));
   }
 </script>
</head>

<script runat="server">
</script>
<% 
    string sURL = Request.QueryString.ToString();
    string sRawURL = Request.RawUrl;
    string sEncodedTargetURL = Request.QueryString[sTargetUrlName];
    string sTargetURL = TokenUtils.decodeText(sEncodedTargetURL);
    UriBuilder ub = new UriBuilder(sTargetURL);
    string sAuthParam = "andrey";
    string sTime = DateTime.Now.ToUniversalTime().ToString("o");
    string sToken = encryptToken(sAuthParamName + "=" + sAuthParam + ";time=" + sTime);
%>        

<body>
<%
    string sAuthUrl = ub.ToString() + (("".Equals(ub.Query)) ? "?" : "&") +
                        sAuthTokenName + "=" + sToken;
    Response.Write("<p>Click following link to authorize access to the <b>'test-target.aspx'</b>:</p>");
    Response.Write("<a href='" + sAuthUrl + "' >" + sAuthUrl + "</a>");
%>
</body>
</html>
